<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.15.9/theme-chalk/index.css">
    <style>
        body{
            margin: 0;
        }
        .container {
            /*margin: 0;*/
            position: relative;
            overflow-y: hidden;
            height: 100vh;
        }
        .background {
            background-image: url('http://rwoyy67xx.hn-bkt.clouddn.com/img/dsBuffer.bmp.png');
            background-repeat: no-repeat;
            background-size: cover;
            height:calc(100% - 100px);
            overflow-y: hidden;
        }
        .center {
            display: flex;
            flex-direction: column;
            height: 100%;
            width: 100%;
        }
        .el-aside {
            background-color:#eaf6fe;
            color: #333;
            padding: 20px;
            line-height: 30px;
            text-align: center;
        }
        .el-aside h3 {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 20px;
        }
        .el-aside ul {
            list-style-type: none;
            padding: 0;
        }
        .el-aside ul li {
            cursor: pointer;
            margin-bottom: 10px;
        }
        .el-main {
            background-color: rgba(255, 255, 255, 0.3);
            color: #333;
            padding: 20px;
            flex-grow: 1;
        }

        .title {
            background-color: #14e5bb;
            text-align: center;
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 20px;
            border-radius: 5px
        }
        .message{
            display: flex;
            justify-content: space-between;
            background-color: #fafafc;
            border-radius: 4px;
            height: 750px;
        }
        .message-list {
            /*border-right: 1px solid #d9d9d9;*/
            height: 100%;
            border-radius:30px;
            margin-right: 20px;
            flex-grow: 1;
            background-color: rgba(255, 255, 255, 0.3);
            border: none !important;

        }
        .message-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-grow: 1;
        }
        .message-sender {
            text-align: center;
            flex-grow: 1;
        }
        .message-unread {
            background-color: #ff4d4f;
            color: #fff;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            line-height: 20px;
            text-align: center;
        }
        .message-close {
            color: #999;
            cursor: pointer;
        }
        .messageView{
            height: 550px;
            flex-grow: 1;
            border-bottom: #999999 solid 1px;
            background-color:#f4f5f7;
            overflow-y: auto;
        }


        .message-item {
            align-items: center;
            flex-grow: 1;
            padding: 5px;
        }
        .message-itemfor:hover {
            background-color: #f5f5f5;
        }
        .message-itemfor{
            display: flex;
            flex-direction: row ;
            justify-content: space-between;
            flex-basis: 100%;
            align-items: center;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .selected {
            display: flex;
            flex-direction: row ;
            justify-content: space-between;

            background-color: #f5f5f5;
        }

        .chat-window {
            background-color: #f4f5f7;
            display: flex;
            flex-direction: column;
            border-radius: 30px;
            background-color: rgba(255, 255, 255, 0.3);
            border: none !important;
            justify-content: space-between;
            flex-grow: 1;
        }

        .typing-info {
            border-bottom: 1px solid #ccc;
            padding-bottom: 10px;
        }

        .emoji-picker {
            margin-left: 10px;
            cursor: pointer;
        }

        .chat-input {
            display: flex;
            align-items: center;
            margin-top: 10px;
            flex-grow: 1;
        }

        .msg_left{
            align-self: flex-start;
            width: 500px;
            /* padding-left: 5px; */
            margin-top: 5px;
            /* border: 1px #1890ff solid; */
        }
        .msg_right{
            margin-right: 20px;
            align-self: flex-end;
            /* padding-right: 20px; */
            margin-top: 5px;
            /* border: 1px #1890ff solid; */
            text-align: right;
        }
        .msg_left_up{
            height: 25px;
            margin: 20px;
        }
        .msg_right_up{
            height: 25px;
            margin: 20px;
        }

        .msg_left_down{
            display: inline-block;
            width: auto;
            /* border: 1px #1890ff solid; */
            padding: 10px;
            margin-left: 45px;
            border-radius: 0% 30% 30% 50%;
            background-color: gold;
            white-space: pre-wrap;
        }

        .msg_right_down{
            display: inline-block;
            width: auto;
            /* border: 1px #1890ff solid; */
            padding: 10px;
            margin-right: 45px;
            border-radius: 30% 0% 50% 30%;
            white-space: pre-wrap;
            background-color: #80b9f2;
        }


        .down{
            width: 680px;
            height: 200px;
            /* border: 1px red solid; */
        }
        .chat-input el-input {
            flex-grow: 1;
            margin-right: 10px;
        }
        .chat-input el-button {
            width: 80px;
        }

        .message-container {
            display: flex;
            flex-direction: column;
            border: 1px solid #ccc;
            padding: 10px;
            height: inherit;
        }

        .recent-messages,
        .create-session {
            flex-grow: 1;
            border: none;
            height: 50vh;
            overflow-y: auto;
        }
        .create-session{

        }

        .recent-messages {
            /*border-bottom: 1px solid #ccc;*/
            padding-bottom: 10px;
        }

        .seng-img{
            height: 20px;
        }
        .input-box {
            /*margin-top: -70px;*/
            margin-bottom: 20px;
            height: auto;
            display: flex;
            align-items: flex-end;
        }
        .input-container{
            display: flex;
            flex: 1;
        }
        .input{
            border: none;
            flex-grow: 1;
        }

        .send-button{
            position: absolute;
            right: 0px;
            bottom: 20px;
            z-index: 1;
        }
        .myHeader{
            width: 100%;
        }
        .message-item-gap {
            height: 20px; /* 设置间隔的高度为10像素 */
        }

    </style>
</head>
<body>
<div id="app">

    <el-container class="container" style="display: flex; flex-direction: column;justify-content: center;">
        <my-header class="myHeader"></my-header>
        <div class="background">

            <el-container class="center" style="display: flex; justify-content: center;">
                <el-aside class="el-aside" v-if="false" style="margin-left: 15%; margin-right: 15%;">
                    <h3><i class="el-icon-edit"></i> 消息中心</h3>
                    <el-menu
                            default-active="5"
                            class="el-menu-vertical-demo"
                            background-color="#eaf6fe"
                            text-color="#6b757b"
                            active-text-color="#2faee3"
                    >
                        <el-menu-item index="2">
                            <i class="el-icon-menu"></i>
                            <span slot="title">回复我的</span>
                        </el-menu-item>
                        <el-menu-item index="3" disabled>
                            <i class="el-icon-document"></i>
                            <span slot="title">@我的</span>
                        </el-menu-item>
                        <el-menu-item index="4">
                            <i class="el-icon-setting"></i>
                            <span slot="title">收到的赞</span>
                        </el-menu-item>
                        <el-menu-item index="5">
                            <i class="el-icon-setting"></i>
                            <span slot="title">我的消息</span>
                        </el-menu-item>
                    </el-menu>
                </el-aside>

                <el-main class="el-main" style="margin-left: 15%; margin-right: 15%; overflow: hidden">
                    <el-row class="title">
                        <div>我的消息</div>
                    </el-row>

                    <el-row class="message">

                        <el-col :span="6" class="message-list" >
                            <div class="message-container">
                                <div class="recent-messages">
                                    <div><h3 style="text-align: center;height: 10px">近期消息</h3></div>
                                    <el-divider></el-divider>
                                    <!-- 近期消息内容 -->
                                    <div class="message-item">
                                        <div :class="curSessionId == item.id ? 'message-item selected' : 'message-itemfor'" v-for="item in sessionList_already" style="margin-top: 5px; border: none #555; border-radius: 8px; padding: 10px; background-color: #f0f0f0; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); transition: background-color 0.3s ease;" :key="item.id" @click="startSession(item.id)">
                                            <el-avatar :size="40" fit="fill" :src="item.toUserImgUrl"></el-avatar>
                                            <div class="message-info">
                                                <span class="message-sender">{{ item.toUserName }}</span>
                                                <span class="message-unread" v-if="item.unReadCount > 0">{{ item.unReadCount }}</span>
                                            </div>
                                            <i class="el-icon-close message-close" @click="delSession(item.id)"></i>
                                        </div>

                                    </div>
                                </div>

                                <div class="create-session">
                                    <div><h3 style="text-align: center;height: 10px">可建立会话</h3></div>
                                    <el-divider></el-divider>

                                    <div class="message-item">
                                        <div :class="curSessionId == item.id ? 'message-item selected' : 'message-itemfor'" v-for="item in sessionList_not" style="margin-top: 5px; border: none #555; border-radius: 8px; padding: 10px; background-color: #f0f0f0; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); transition: background-color 0.3s ease;" :key="item.id" class="box" @click="createSession(item.id)">
                                            <el-avatar :size="40" fit="fill" :src="item.imgUrl"></el-avatar>
                                            <div class="message-sender">{{item.userName}}</div>
                                        </div>

                                    </div>

                                </div>
                            </div>
                        </el-col>

                        <!-- 聊天消息 -->
                        <el-col :span="18" class="chat-window" style="margin-left: 5px; height: calc(100% - 70px)">
                            <div>
                                <div class="typing-info">
                                    <h3 id="selectedUserName" style="text-align: center;height: 15px">请选择好友聊天</h3>
                                </div>
                                <div class="messageView" ref="chatContainer" id="msg_end">

                                    <div v-for="(item, index) in list" :key="index" :class="item.fromUserId === curUserId ? 'msg_right' : 'msg_left'">

                                        <div class="msg_right_up" v-if="item.fromUserId === curUserId">
                                            <!--                        {{item.fromUserName}}-->
                                            <el-avatar :size="40" fit="fill" :src="item.fromUserImgUrl"></el-avatar>
                                        </div>

                                        <div class="msg_left_up" v-else>
                                            <el-avatar :size="40" fit="fill" :src="item.fromUserImgUrl"></el-avatar>
                                            <!--                        {{item.fromUserName}}-->
                                        </div>

                                        <div :class="item.fromUserId === curUserId ? 'msg_right_down' : 'msg_left_down'">{{item.content}}</div><br>

                                    </div>
                                    <!--            <el-divider></el-divider>-->
                                </div>
                                <!--              <div class="seng-img"> 站位 </div>-->
                                <!-- 输入框 -->
                                <div class="input-box" >
                                    <div></div>
                                    <el-input
                                            class="input"
                                            type="textarea"
                                            :rows="5"
                                            placeholder="请输入内容，回车发送！"
                                            v-model="textarea"
                                            @keyup.enter.native="sendMsg"
                                    ></el-input>
                                    <el-button @click="sendMsg" class="send-button">发送</el-button>
                                </div>
                            </div>
                        </el-col>

                    </el-row>
                </el-main>

            </el-container>

        </div>
    </el-container>

</div>

</body>
<!--import axios-->
<script src="https://cdn.bootcss.com/axios/0.18.0/axios.min.js"></script>
<!-- import Vue before Element -->
<script src="https://cdn.staticfile.org/vue/2.6.14/vue.min.js"></script>
<!-- import JavaScript -->
<script src="https://cdn.staticfile.org/element-ui/2.15.9/index.min.js"></script>
<!--引入自己的js文件-->
<script src="js/my-header.js"></script>

<script>
    let v = new Vue({
        el:"body>div",
        data(){
            return{
                textarea: "",             //文本框输入信息
                list: [],                 //消息列表
                curUserId: "",            //本人id
                curUserName: "",          //本人名字
                curSessionId: '',         //本人会话id
                curSession:'',            //会话
                toUserName:'',            //聊天对象名字
                curImgUrl:"",             //用户头像
                sessionList_already:[],   //已创建会话列表
                sessionList_not:[],       //未创建会话列表
                user:localStorage.user?JSON.parse(localStorage.user):null,
            }
        },
        created() { // 页面创建生命周期函数
            this.curUserId = this.user.userid;
            this.curUserName = this.user.username;
            this.curImgUrl = this.user.imgUrl;
            console.log("curUserName",this.curUserName);
            this.getSessionListNot();
            this.sessionListAlready();
            this.startSession(99999999);
        },
        updated() {

        },
        destroyed: function () { // 离开页面生命周期函数
            this.websocketclose();
        },
        methods: {
            initWebSocket: function (userId, sessionId) {
                // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
                this.websock = new WebSocket("ws://localhost:8088/websocket/"+userId+"/"+sessionId);
                this.websock.onopen = this.websocketonopen;
                this.websock.onerror = this.websocketonerror;
                this.websock.onmessage = this.websocketonmessage;
                this.websock.onclose = this.websocketclose;
            },
            websocketonopen: function () {
                console.log("WebSocket连接成功");
                console.log(this.websock);
            },
            websocketonerror: function (e) {
                console.log("WebSocket连接发生错误", e);
            },
            websocketonmessage: function (e) {
                let data = JSON.parse(e.data);
                if (data instanceof Array) {
                    // 列表数据
                    this.sessionList_already = data
                } else {
                    // 消息数据
                    this.list.push(data);
                }
            },
            websocketclose: function (e) {
                if (this.curUserId != null) {
                    if (this.curSessionId != null) {
                        this.initWebSocket(this.curUserId, this.curSessionId);
                    } else {
                        this.initWebSocket(this.curUserId, 99999999);
                    }
                }
                console.log("connection closed", e);
            },
            // 消息发送
            sendMsg() {
                if (this.curSessionId === ''||this.curSessionId == undefined) {
                    return this.$message.error("请选择左边的对话框开始聊天!");
                }
                const data = {
                    fromUserId: this.curUserId,
                    fromUserName: this.curUserName,
                    content: this.textarea,
                    fromUserImgUrl: this.curImgUrl // 添加用户头像信息
                };
                this.list.push(data);
                console.log(data);
                console.log(this.list);
                this.websock.send(this.textarea);

                this.textarea = '';
                this.$nextTick(() => {
                    this.scrollToBottom();
                });
            },
            //
            scrollToBottom() {
                const chatContainer = this.$refs.chatContainer;
                chatContainer.scrollTop = chatContainer.scrollHeight;
            },
            // 获取可建立会话列表
            getSessionListNot() {
                let thus = this;
                axios.get("/v1/sessionList/not?id=" + this.curUserId)
                    .then(function (response) {
                        if (response.data.code !== 1) {
                            return thus.$message.error(response.data.msg);
                        }
                        thus.sessionList_not = response.data.data;
                        // console.log(thus.sessionList_not);
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            // 获取已存在的会话列表
            sessionListAlready() {
                let thus = this;
                axios.get("/v1/sessionList/already?id=" + this.curUserId)
                    .then(function (response) {
                        if (response.data.code !== 1) {
                            return thus.$message.error(response.data.msg);
                        }
                        thus.sessionList_already = response.data.data;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            // 创建会话
            createSession(toUserId) {
                let thus = this;
                axios.get("/v1/sessionList/create?id=" + this.curUserId + "&toUserId=" + toUserId )
                    .then(function (response) {
                        if (response.data.code !== 1) {
                            return thus.$message.error(response.data.msg);
                        }
                        thus.getSessionListNot();
                        thus.sessionListAlready();
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },

            // 开始会话
            startSession(sessionId) {
                if (this.websock != undefined) {
                    this.websock.close();
                }
                this.curSessionId = sessionId;
                this.initWebSocket(this.curUserId, sessionId);
                this.msgList(sessionId);
                //console.log(0);
                console.log("sessionID = " + sessionId);
                //this.getSession(sessionId);
                //console.log(4);
            },

            //获取会话
            async getSession(sessionId){
                try {
                    console.log(1);
                    const response = await axios.get("/v1/sessionList/getSession?sessionId=" + sessionId);
                    if (response.data.code !== 1) {
                        console.log(response);
                        console.log(2);
                        return this.$message.error(response.data.msg);
                    }
                    const selectedUser = response.data;
                    if(selectedUser){
                        const selectdUserName = document.getElementById('selectdUserName');
                        selectdUserName.textContent = selectedUser;
                        console.log(3);
                    }else {
                        console.log(selectedUser);
                    }
                } catch (error) {
                    console.log(error);
                }
            },

            // 删除会话
            delSession(sessionId) {
                let thus = this;
                axios.get("/v1/sessionList/delect?sessionId=" + sessionId)
                    .then(function (response) {
                        if (response.data.code !== 1) {
                            return thus.$message.error(response.data.msg);
                        }
                        thus.getSessionListNot();
                        thus.sessionListAlready();
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },

            // 获取消息数据
            msgList(sessionId) {
                let thus = this;
                axios.get("/v1/message/messageList?sessionId=" + sessionId)
                    .then(function (response) {
                        if (response.data.code === -1) {
                            return thus.$message.error(response.data.msg);
                        }
                        thus.list = response.data.data;
                        console.log(thus.list);
                        // 从新获取列表
                        thus.sessionListAlready();
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            }
        },
    })

</script>

</html>